package com.shihb.akka.actor

import akka.actor.{Actor, ActorRef, ActorSystem, Props}

/**
 * Description:Actord快速入门-自我通讯
 * 实现发送hello 回应收到hello,回应hello too
 * 实现发送ok 回应收到ok,回应ok too
 *实现发送exit 退出系统
 * @author shihb
 * @date 2020/10/2 19:55
 */
/**
 * 当我们继承Actor后就是一个Actor,核心方法receive方法重写
 */
class SayHelloActor extends Actor{
  /**
   * receive方法,会被该Actor的MailBox(实现Runable接口)调用
   * 当Actor的MailBox接收到消息,就会调用receive
   * type Receive = scala.PartialFunction[scala.Any, scala.Unit]
   * 这边是一个偏函数
   * @return
   */
  override def receive: Receive = {
    case "hello"=>println("收到hello,回应hello too")
    case "ok"=>println("收到ok,回应ok too")
    case "exit"=>{
      println("接收到退出指令,退出系统")
      context.stop(self) //停止actorRef
      context.system.terminate()//停止actorSystem
    }
    case _=>println("匹配不到")
  }
}
object SayHelloActorDemo{
  // 1、先创建一个ActorSystem,专门用于创建Actor
  private val actorFactory: ActorSystem = ActorSystem("ActorFactory")
  // 2、创建Actor并返回ActorRef
  // (1)Props[SayHelloActor]创建了SayHelloActor的实例，目前使用反射
  // (2)SayHelloActor 给Actor取名
  // (3)ssayHelloActorRef: ActorRef就是Props[SayHelloActor]的引用
  private val sayHelloActorRef: ActorRef = actorFactory.actorOf(Props[SayHelloActor], "SayHelloActor")
  def main(args: Array[String]): Unit = {
    // 给SayHelloActor发消息!
    sayHelloActorRef!"hello"
    sayHelloActorRef!"ok"
    sayHelloActorRef!"hello!"
    // 如何退出Actor
    sayHelloActorRef!"exit"
  }

}
